import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Users } from "../../entities/Users.entity"

@Provide()
export class UsersService {
  @InjectEntityModel(Users)
  repo!: Repository<Users>

  async list(page: number = 1, pageSize: number = 10, filters?: {
    nickname?: string;
    isDisabled?: boolean;
    phone?: string;
  }) {
    const query = this.repo.createQueryBuilder('user');
    
    // 添加筛选条件
    if (filters) {
      if (filters.nickname) {
        query.andWhere('user.nickname LIKE :nickname', { nickname: `%${filters.nickname}%` });
      }
      if (filters.isDisabled !== undefined) {
        query.andWhere('user.isDisabled = :isDisabled', { isDisabled: filters.isDisabled });
      }
      if (filters.phone) {
        query.andWhere('user.phone LIKE :phone', { phone: `%${filters.phone}%` });
      }
    }
    
    // 分页和排序
    query.skip((page - 1) * pageSize)
         .take(pageSize)
         .orderBy('user.id', 'DESC');
    
    const [data, total] = await query.getManyAndCount();

    return {
      total,
      items: data,
    }
  }
}
